import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Goods } from './entities/goods.entity';
import { CreateGoodsDto } from './dto/create-goods.dto';
import { UpdateGoodsDto } from './dto/update-goods.dto';
import { MinioService } from '../minio/minio.service';
import { BufferedFile } from '../minio/file.model';

@Injectable()
export class GoodsService {
  constructor(
    @InjectRepository(Goods)
    private readonly goodsRepository: Repository<Goods>,
    private readonly minioService: MinioService,
  ) {}

  async create(createGoodsDto: CreateGoodsDto) {
    const goods = this.goodsRepository.create(createGoodsDto);
    return await this.goodsRepository.save(goods);
  }

  async uploadImages(id: number, files: BufferedFile[]) {
    const goods = await this.findOne(id);
    if (!goods) {
      throw new NotFoundException(`商品 #${id} 不存在`);
    }

    // 删除旧图片
    if (goods.images && goods.images.length > 0) {
      for (const imageUrl of goods.images) {
        try {
          const imageName = imageUrl.split('/').pop();
          if (imageName) {
            await this.minioService.delete(imageName);
          }
        } catch (error) {
          console.error('删除旧图片失败:', error);
        }
      }
    }

    // 上传新图片
    const uploadedUrls = await Promise.all(
      files.map((file) => this.minioService.upload(file, 'goods/')),
    );

    // 更新商品图片URLs
    goods.images = uploadedUrls;
    await this.goodsRepository.save(goods);

    return goods;
  }

  async findAll() {
    return await this.goodsRepository.find({
      relations: ['seller', 'category', 'community'],
    });
  }

  async findOne(id: number) {
    const goods = await this.goodsRepository.findOne({
      where: { id },
      relations: ['seller', 'category', 'community'],
    });

    if (!goods) {
      throw new NotFoundException(`商品 #${id} 不存在`);
    }

    return goods;
  }

  async update(id: number, updateGoodsDto: UpdateGoodsDto) {
    const goods = await this.findOne(id);
    await this.goodsRepository.update(id, updateGoodsDto);
    return this.findOne(id);
  }

  async remove(id: number) {
    const goods = await this.findOne(id);

    // 删除所有图片
    if (goods.images && goods.images.length > 0) {
      for (const imageUrl of goods.images) {
        try {
          const imageName = imageUrl.split('/').pop();
          if (imageName) {
            await this.minioService.delete(imageName);
          }
        } catch (error) {
          console.error('删除商品图片失败:', error);
        }
      }
    }

    await this.goodsRepository.delete(id);
  }
}
